﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Configuration;
using Newtonsoft.Json.Linq;
using Quartz.JobClass.userKeyparmsDTO;
using System.Dynamic;
using System.Reflection;

namespace Quartz.JobClass
{
    class CommonHelper
    {
        static DataTable dt_setting = Platform.Data.OracleHelper.ExecuteDataset(Platform.Configuration.ConfigHelper.BusinessConnString, CommandType.Text, "select * from s_words where belongid=111").Tables[0];
        public CommonHelper()
        {
            
        }
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            DateTime dt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
            TimeSpan ts = DateTime.Now - dt1;
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        /// <summary>
        /// Web调用
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="MethodName"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static string QueryPostWebService(String URL, String MethodName, string body)
        {
            //string rid = System.Guid.NewGuid().ToString();
            string requeststr = URL;
            string responsestr = "";
            //string t = GetTimeStamp();
            LogHelper.Info("开始请求地址：" + URL + "/" + MethodName );
            LogHelper.Info(MethodName+"请求参数：" + body);

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback (   delegate { return true; }        );
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName );
            request.Method = "POST";
            //request.ContentType = "text/xml; charset=utf-8";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.ContentType = "application/json";//charset=UTF-8
            Encoding encoding = Encoding.UTF8;
            /// 设置凭证与超时时间
            request.Credentials = CredentialCache.DefaultCredentials;
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Timeout = 10000;//设置timeout 10S
            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                responsestr= reader.ReadToEnd();
            }
            LogHelper.Info(MethodName+"返回结果：" + responsestr);
            return responsestr;
        }
        /// <summary>
        /// 读取文本内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetContentByTxt(string path)
        {
            string conStr = "";
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
                while (!reader.EndOfStream)
                {
                    conStr = conStr+reader.ReadLine();
                }
            }
            catch (Exception)
            {
                conStr = "";
            }
            return conStr;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            string KeySecret= "";
            string _token = "";
            SpHelper _SpHelper = new SpHelper();
            
            
            try
            {
                string paramstr = "";
                paramstr += CommonHelper.GetTimeStamp() + "";
                //1.获取安全令牌 
                DataSet ds = _SpHelper.GetParamsDataSource("<PROCEDURE>", "SELECT;GSC_PGETCURRENTUSERKEY;" + paramstr, "");
                if (ds.Tables[0].Rows[0]["I_YOUXIAO"].ToString()== "1")//
                {
                    KeySecret = ds.Tables[0].Rows[0]["KEYSECRET"].ToString();
                    _token = ds.Tables[0].Rows[0]["TOKEN"].ToString();
                }
                else if (ds.Tables[0].Rows[0]["I_YOUXIAO"].ToString() == "0")//获取token 并更新到数据库
                {
                    LogHelper.Info("token值失效，开始重新获取...");
                    KeySecret = ds.Tables[0].Rows[0]["KEYSECRET"].ToString();

                    //调取安全令牌
                    userKeyparms _userKeyparms = new userKeyparms()
                    {
                        parms = new Parms()
                        {
                            UserName = dt_setting.Select("WORDSCONTENT='GSC_UserName'")[0]["WORDSVALUE"].ToString(),//Platform.Common.KeyValueHelper.GetValue("GSC_UserName"),
                            Expires = Convert.ToInt32(dt_setting.Select("WORDSCONTENT='GSC_Expires'")[0]["WORDSVALUE"].ToString()),
                            KeyId = dt_setting.Select("WORDSCONTENT='GSC_KeyId'")[0]["WORDSVALUE"].ToString(),
                            KeySecret = KeySecret
                        }
                    };

                    string postUrl = dt_setting.Select("WORDSCONTENT='GSC_Url'")[0]["WORDSVALUE"].ToString();
                    string MethodName = ConfigurationManager.AppSettings["GetToken"];
                    string body = Json6Helper.SerializeObject(_userKeyparms);
                    
                    string responsestr = QueryPostWebService(postUrl, MethodName, body);//File.ReadAllText(@"D:\A_WorkSpace\pudongveolia\CSMS外部接口\非居累计加价\gettoken.txt");////待修改
                    
                    JObject jsonObj = JObject.Parse(responsestr);
                    _token = Json6Helper.GetJsonValue(jsonObj.Children(), "Token");
                    string errCode = jsonObj["errCode"].ToString();
                    string errMsg = jsonObj["errMsg"].ToString();

                    if (errCode == "0")
                    {
                        ds = _SpHelper.GetParamsDataSource("<PROCEDURE>", "UPDATE;GSC_PSETCURRENTUSERKEY;" + _token + ";" + Convert.ToInt32(dt_setting.Select("WORDSCONTENT='GSC_Expires'")[0]["WORDSVALUE"].ToString()), "");

                    }
                    else
                    {
                        LogHelper.Error("调用GetToken异常：{0}", errMsg);
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取安全令牌异常：{0}", ex.Message);
                _token = "";
                return _token;
            }
            return _token;
        }
        /// <summary>
        /// 将List{T}转成DataTable
        /// </summary>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }

        /// <summary>
        /// dataTable 转换为 List
        /// 属性赋值
        /// </summary>
        /// <typeparam name="T">类别</typeparam>
        /// <param name="dataTable">数据</param>
        /// <param name="obj">类别实体</param>
        /// <returns></returns>
        public static System.Collections.Generic.List<T> TableConvertList<T>(DataTable dataTable, T obj)
        {
            DataTable dtTemp = dataTable.Copy();
            System.Collections.Generic.List<T> list = new System.Collections.Generic.List<T>();
            Type type = obj.GetType();
            foreach (DataRow dr in dataTable.Rows)
            {
                obj = (T)type.Assembly.CreateInstance(type.FullName);
                for (int i = 0; i < dtTemp.Columns.Count; i++)
                {
                    try
                    {
                        Type t = type.GetProperty(dtTemp.Columns[i].Caption).PropertyType;
                        if (t.Name.ToUpper() == typeof(Int32).Name.ToUpper())
                        {
                            type.GetProperty(dtTemp.Columns[i].Caption).SetValue(obj, Convert.ToInt32(dr[dtTemp.Columns[i].Caption]), null);
                        }
                        else
                        {
                            type.GetProperty(dtTemp.Columns[i].Caption).SetValue(obj, dr[dtTemp.Columns[i].Caption], null);
                        }
                    }
                    catch(Exception ex)
                    {
                        //dtTemp.Columns.RemoveAt(i); i--;
                    }
                }
                list.Add(obj);
            }
            return list;
        }

        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// 在指定的表中增加字符列，并赋初值
        /// </summary>
        /// <param name="dt">待增加选定列的表</param>
        /// <param name="colName">列名</param>
        /// <param name="defaultValue">默认值</param>
        public static void AddStringColumn(DataTable dt, string colName, string defaultValue)
        {
            dt.Columns.Add(new DataColumn(colName, typeof(string)));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][dt.Columns.Count - 1] = defaultValue;
            }
        }
        /// <summary>
        /// 在指定的表中增加整形列，并赋初值
        /// </summary>
        /// <param name="dt">待增加选定列的表</param>
        /// <param name="colName">列名</param>
        /// <param name="defaultValue">默认值</param>
        public static void AddIntColumn(DataTable dt, string colName, decimal defaultValue)
        {
            dt.Columns.Add(new DataColumn(colName, typeof(decimal)));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][dt.Columns.Count - 1] = defaultValue;
            }
        }

    }
    public class LogUtil
    {
        private static ILog _logger = null;

        static LogUtil()
        {
            log4net.Config.XmlConfigurator.Configure();
        }

        protected static ILog Logger
        {
            get
            {
                if (_logger == null)
                {
                    _logger = log4net.LogManager.GetLogger("CDE.Logger");
                }

                return _logger;
            }
        }
        public static void Debug(string msg)
        {
            Logger.Debug(msg);
        }

        public static void Debug(string format, params object[] ps)
        {
            Logger.DebugFormat(format, ps);
        }

        public static void Info(string msg)
        {
            Logger.Info(msg);
        }

        public static void Info(string format, params object[] ps)
        {
            Logger.InfoFormat(format, ps);
        }

        public static void Warn(string msg)
        {
            Logger.Warn(msg);
        }

        public static void Warn(string format, params object[] ps)
        {
            Logger.WarnFormat(format, ps);
        }

        public static void Error(string msg)
        {
            Logger.Error(msg);
        }

        public static void Error(string format, params object[] ps)
        {
            Logger.ErrorFormat(format, ps);
        }
    }
}
